{% extends 'dashboard/base.html' %}
{% load static %}

{% block title %}系统分析 - 后台管理{% endblock %}

{% block extra_css %}
<style>
    .stat-card {
        transition: transform 0.2s;
        border-left: 4px solid;
    }
    .stat-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    .stat-card.primary { border-left-color: #0d6efd; }
    .stat-card.success { border-left-color: #198754; }
    .stat-card.warning { border-left-color: #ffc107; }
    .stat-card.info { border-left-color: #0dcaf0; }
    .stat-card.danger { border-left-color: #dc3545; }
    .stat-card.secondary { border-left-color: #6c757d; }
    
    .chart-container {
        position: relative;
        height: 300px;
        margin-bottom: 20px;
    }
    
    .mini-chart {
        height: 80px;
    }
    
    .progress-thin {
        height: 6px;
    }
</style>
{% endblock %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">系统数据分析</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="exportCharts()">
                <i class="bi bi-download"></i> 导出图表
            </button>
            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="refreshData()">
                <i class="bi bi-arrow-clockwise"></i> 刷新数据
            </button>
        </div>
    </div>
</div>

<!-- 关键指标卡片 -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card primary h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <div class="text-primary text-uppercase small fw-bold">总用户数</div>
                        <div class="h3 mb-0">{{ total_users }}</div>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-people fs-1 text-primary opacity-25"></i>
                    </div>
                </div>
                <div class="mt-2">
                    <span class="text-success small">
                        <i class="bi bi-arrow-up"></i> 本周新增 {{ new_users_week }} 人
                    </span>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card success h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <div class="text-success text-uppercase small fw-bold">总活动数</div>
                        <div class="h3 mb-0">{{ total_activities }}</div>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-calendar-event fs-1 text-success opacity-25"></i>
                    </div>
                </div>
                <div class="mt-2">
                    <div class="small text-muted">
                        已通过: {{ approved_activities }} | 待审核: {{ pending_activities }}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card info h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <div class="text-info text-uppercase small fw-bold">活动参与</div>
                        <div class="h3 mb-0">{{ total_registrations }}</div>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-person-check fs-1 text-info opacity-25"></i>
                    </div>
                </div>
                <div class="mt-2">
                    <div class="small text-muted">
                        签到率: {{ checkin_rate }}% ({{ total_checkins }}/{{ total_registrations }})
                    </div>
                    <div class="progress progress-thin mt-1">
                        <div class="progress-bar bg-info" style="width: {{ checkin_rate }}%"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card warning h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <div class="text-warning text-uppercase small fw-bold">积分系统</div>
                        <div class="h3 mb-0">{{ total_points }}</div>
                    </div>
                    <div class="align-self-center">
                        <i class="bi bi-coin fs-1 text-warning opacity-25"></i>
                    </div>
                </div>
                <div class="mt-2">
                    <div class="small text-muted">
                        有积分用户: {{ active_points_users }} | 兑换次数: {{ total_exchanges }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 第一行图表 -->
<div class="row mb-4">
    <!-- 用户增长趋势 -->
    <div class="col-xl-8 col-lg-7">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">平台增长趋势</h6>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary active" data-period="month">月度</button>
                    <button class="btn btn-outline-primary" data-period="quarter">季度</button>
                </div>
            </div>
            <div class="card-body">
                <div class="chart-container">
                    <canvas id="growthTrendChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 活动状态分布 -->
    <div class="col-xl-4 col-lg-5">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">活动状态分布</h6>
            </div>
            <div class="card-body">
                <div class="chart-container">
                    <canvas id="activityStatusChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 第二行图表 -->
<div class="row mb-4">
    <!-- 活动分类分布 -->
    <div class="col-xl-4 col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">活动分类分布</h6>
            </div>
            <div class="card-body">
                <div class="chart-container">
                    <canvas id="categoryDistributionChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 用户类型分布 -->
    <div class="col-xl-4 col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">用户类型分布</h6>
            </div>
            <div class="card-body">
                <div class="chart-container">
                    <canvas id="userTypeChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 积分类型分布 -->
    <div class="col-xl-4 col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">积分获取类型</h6>
            </div>
            <div class="card-body">
                <div class="chart-container">
                    <canvas id="pointsTypeChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 第三行图表 -->
<div class="row">
{#    <!-- 热门活动 -->#}
{#    <div class="col-xl-6">#}
{#        <div class="card shadow mb-4">#}
{#            <div class="card-header py-3">#}
{#                <h6 class="m-0 font-weight-bold text-primary">热门活动排行榜</h6>#}
{#            </div>#}
{#            <div class="card-body">#}
{#                <div class="chart-container">#}
{#                    <canvas id="popularActivitiesChart"></canvas>#}
{#                </div>#}
{#            </div>#}
{#        </div>#}
{#    </div>#}

    <!-- 平台活跃度 -->
    <div class="col-xl-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">平台活跃度概览</h6>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-4">
                        <div class="border rounded p-3 mb-3">
                            <div class="h4 text-primary">{{ active_users_recent }}</div>
                            <div class="small text-muted">月活跃用户</div>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="border rounded p-3 mb-3">
                            <div class="h4 text-success">{{ total_follows }}</div>
                            <div class="small text-muted">关注关系</div>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="border rounded p-3 mb-3">
                            <div class="h4 text-info">{{ total_messages }}</div>
                            <div class="small text-muted">私信总数</div>
                        </div>
                    </div>
                </div>
                <div class="mt-3">
                    <h6 class="text-muted">用户参与度</h6>
                    <div class="progress mb-2">
                        <div class="progress-bar bg-success" style="width: {{ active_users|divisibleby:total_users|default:0|floatformat:2 }}%">
                            活跃用户: {{ active_users }}
                        </div>
                    </div>
                    <div class="progress mb-2">
                        <div class="progress-bar bg-info" style="width: {{ active_points_users|divisibleby:total_users|default:0|floatformat:2 }}%">
                            积分用户: {{ active_points_users }}
                        </div>
                    </div>
                    <div class="progress">
                        <div class="progress-bar bg-warning" style="width: {{ active_users_recent|divisibleby:total_users|default:0|floatformat:2 }}%">
                            月活跃: {{ active_users_recent }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 数据更新时间 -->
<div class="row">
    <div class="col-12">
        <div class="text-center text-muted small">
            <i class="bi bi-clock"></i> 数据更新时间: {% now "Y-m-d H:i:s" %}
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
<script>
    // 注册插件
    Chart.register(ChartDataLabels);

    // 颜色配置
    const chartColors = {
        primary: '#4e73df',
        success: '#1cc88a',
        info: '#36b9cc',
        warning: '#f6c23e',
        danger: '#e74a3b',
        secondary: '#858796',
        light: '#f8f9fc'
    };

    // 增长趋势图表
    const monthlyActivityData = {{ monthly_activity_data|safe }};
    const monthlyUserData = {{ monthly_user_data|safe }};
    const monthlyRegistrationData = {{ monthly_registration_data|safe }};

    const growthTrendCtx = document.getElementById('growthTrendChart').getContext('2d');
    const growthTrendChart = new Chart(growthTrendCtx, {
        type: 'line',
        data: {
            labels: monthlyActivityData.map(item => item.month),
            datasets: [
                {
                    label: '新增用户',
                    data: monthlyUserData.map(item => item.count),
                    borderColor: chartColors.primary,
                    backgroundColor: chartColors.primary + '20',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: '新增活动',
                    data: monthlyActivityData.map(item => item.count),
                    borderColor: chartColors.success,
                    backgroundColor: chartColors.success + '20',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: '活动报名',
                    data: monthlyRegistrationData.map(item => item.count),
                    borderColor: chartColors.info,
                    backgroundColor: chartColors.info + '20',
                    tension: 0.4,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                },
                tooltip: {
                    mode: 'index',
                    intersect: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        drawBorder: false
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });

    // 活动状态分布图表
    const statusStats = {{ status_stats|safe }};
    const statusLabels = {
        'pending': '待审核',
        'approved': '已通过',
        'rejected': '已拒绝',
        'cancelled': '已取消',
        'completed': '已完成'
    };

    const activityStatusCtx = document.getElementById('activityStatusChart').getContext('2d');
    const activityStatusChart = new Chart(activityStatusCtx, {
        type: 'doughnut',
        data: {
            labels: statusStats.map(item => statusLabels[item.status] || item.status),
            datasets: [{
                data: statusStats.map(item => item.count),
                backgroundColor: [
                    chartColors.warning,
                    chartColors.success,
                    chartColors.danger,
                    chartColors.secondary,
                    chartColors.info
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                },
                datalabels: {
                    color: '#fff',
                    formatter: (value, ctx) => {
                        return value;
                    }
                }
            }
        }
    });

    // 活动分类分布图表
    const categoryStats = {{ category_stats|safe }};
    const categoryDistributionCtx = document.getElementById('categoryDistributionChart').getContext('2d');
    const categoryDistributionChart = new Chart(categoryDistributionCtx, {
        type: 'pie',
        data: {
            labels: categoryStats.map(item => item.name),
            datasets: [{
                data: categoryStats.map(item => item.activity_count),
                backgroundColor: [
                    chartColors.primary,
                    chartColors.success,
                    chartColors.info,
                    chartColors.warning,
                    chartColors.danger,
                    chartColors.secondary
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });

    // 用户类型分布图表
    const userTypeStats = {{ user_type_stats|safe }};
    const userTypeLabels = {
        'normal': '普通用户',
        'admin': '管理员',
        'super_admin': '超级管理员'
    };

    const userTypeCtx = document.getElementById('userTypeChart').getContext('2d');
    const userTypeChart = new Chart(userTypeCtx, {
        type: 'polarArea',
        data: {
            labels: userTypeStats.map(item => userTypeLabels[item.user_type] || item.user_type),
            datasets: [{
                data: userTypeStats.map(item => item.count),
                backgroundColor: [
                    chartColors.primary,
                    chartColors.success,
                    chartColors.warning
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });

    // 积分类型分布图表
    const pointsTypeStats = {{ points_type_stats|safe }};
    const pointsTypeLabels = {
        'activity_create': '创建活动',
        'activity_join': '参加活动',
        'activity_checkin': '活动签到',
        'comment': '发表评论',
        'rating': '评分活动',
        'exchange': '积分兑换',
        'admin_adjust': '管理员调整'
    };

    const pointsTypeCtx = document.getElementById('pointsTypeChart').getContext('2d');
    const pointsTypeChart = new Chart(pointsTypeCtx, {
        type: 'bar',
        data: {
            labels: pointsTypeStats.map(item => pointsTypeLabels[item.type] || item.type),
            datasets: [{
                label: '积分数量',
                data: pointsTypeStats.map(item => item.total_points),
                backgroundColor: chartColors.info,
                borderColor: chartColors.info,
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });

    // 热门活动图表
    const popularActivities = {{ popular_activities|safe }};
    const popularActivitiesCtx = document.getElementById('popularActivitiesChart').getContext('2d');
    const popularActivitiesChart = new Chart(popularActivitiesCtx, {
        type: 'horizontalBar',
        data: {
            labels: popularActivities.map(item => item.title.length > 20 ? item.title.substring(0, 20) + '...' : item.title),
            datasets: [{
                label: '参与人数',
                data: popularActivities.map(item => item.registration_count),
                backgroundColor: chartColors.success,
                borderColor: chartColors.success,
                borderWidth: 1
            }]
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                x: {
                    beginAtZero: true
                }
            }
        }
    });

    // 工具函数
    function exportCharts() {
        const link = document.createElement('a');
        link.download = '系统分析报告_' + new Date().toISOString().split('T')[0] + '.png';
        
        // 创建一个临时的canvas来合并所有图表
        const tempCanvas = document.createElement('canvas');
        const tempCtx = tempCanvas.getContext('2d');
        
        // 这里简化实现，实际应该遍历所有图表并导出
        growthTrendChart.toBase64Image().then(url => {
            link.href = url;
            link.click();
        });
    }

    function refreshData() {
        location.reload();
    }

    // 时间周期切换
    document.querySelectorAll('[data-period]').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('[data-period]').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            // 这里可以添加根据周期重新加载数据的逻辑
        });
    });

    // 自动刷新数据（每5分钟）
    setInterval(refreshData, 5 * 60 * 1000);
</script>
{% endblock %}